// VideoInfo 组件的业务逻辑函数

export { render } from './html.js';

/**
 * 绑定事件监听器
 * @param {VideoInfo} component - 组件实例
 */
export function bindEvents(component) {
    // 关注按钮事件
    const followBtn = component.shadowRoot.querySelector('.follow-btn');
    followBtn?.addEventListener('click', () => handleFollow(component));

    // 话题标签点击事件
    const hashtags = component.shadowRoot.querySelectorAll('.hashtag');
    hashtags.forEach(hashtag => {
        hashtag.addEventListener('click', (e) => {
            const tag = e.currentTarget.getAttribute('data-tag');
            handleHashtagClick(component, tag);
        });
    });

    // 作者头像点击事件
    const authorInfo = component.shadowRoot.querySelector('.author-info');
    authorInfo?.addEventListener('click', () => handleAuthorClick(component));

    // 音乐碟片点击事件
    const musicDisc = component.shadowRoot.querySelector('.music-disc');
    musicDisc?.addEventListener('click', () => handleMusicToggle(component));
}

/**
 * 处理关注按钮点击
 * @param {VideoInfo} component - 组件实例
 */
export function handleFollow(component) {
    component.data.isFollowing = !component.data.isFollowing;
    
    const followBtn = component.shadowRoot.querySelector('.follow-btn');
    const followIcon = component.shadowRoot.querySelector('.follow-icon');
    const followText = component.shadowRoot.querySelector('.follow-text');
    
    followBtn.classList.toggle('following', component.data.isFollowing);
    followIcon.setAttribute('name', component.data.isFollowing ? 'check' : 'plus');
    followText.textContent = component.data.isFollowing ? '已关注' : '关注';
    
    // 触发关注动画
    followBtn.classList.add('animate-follow');
    setTimeout(() => followBtn.classList.remove('animate-follow'), 300);
    
    // 派发自定义事件
    component.dispatchEvent(new CustomEvent('follow-changed', {
        detail: { 
            author: component.data.author, 
            isFollowing: component.data.isFollowing 
        }
    }));
}

/**
 * 处理话题标签点击
 * @param {VideoInfo} component - 组件实例
 * @param {string} tag - 话题标签
 */
export function handleHashtagClick(component, tag) {
    // 派发话题点击事件
    component.dispatchEvent(new CustomEvent('hashtag-clicked', {
        detail: { tag }
    }));
}

/**
 * 处理作者点击
 * @param {VideoInfo} component - 组件实例
 */
export function handleAuthorClick(component) {
    // 派发作者点击事件
    component.dispatchEvent(new CustomEvent('author-clicked', {
        detail: { 
            author: component.data.author,
            avatar: component.data.authorAvatar 
        }
    }));
}

/**
 * 处理音乐播放切换
 * @param {VideoInfo} component - 组件实例
 */
export function handleMusicToggle(component) {
    const audio = component.shadowRoot.querySelector('.background-audio');
    const musicDisc = component.shadowRoot.querySelector('.music-disc');
    
    if (!audio || !audio.src) {
        console.warn('没有可播放的音乐文件');
        return;
    }
    
    if (component.data.isPlaying) {
        // 暂停音乐
        audio.pause();
        component.data.isPlaying = false;
        musicDisc.classList.remove('spinning');
    } else {
        // 播放音乐
        audio.play().then(() => {
            component.data.isPlaying = true;
            musicDisc.classList.add('spinning');
        }).catch(error => {
            console.error('音乐播放失败:', error);
        });
    }
    
    // 派发音乐状态变化事件
    component.dispatchEvent(new CustomEvent('music-toggle', {
        detail: { 
            isPlaying: component.data.isPlaying,
            musicName: component.data.backgroundMusicName 
        }
    }));
}

/**
 * 自动播放背景音乐
 * @param {VideoInfo} component - 组件实例
 */
export function autoPlayMusic(component) {
    const audio = component.shadowRoot.querySelector('.background-audio');
    const musicDisc = component.shadowRoot.querySelector('.music-disc');
    
    // 检查是否有音乐源
    if (!audio || !component.data.backgroundMusic) {
        // 没有音乐时停止播放并重置状态
        if (audio) {
            audio.pause();
        }
        component.data.isPlaying = false;
        if (musicDisc) {
            musicDisc.classList.remove('spinning');
        }
        return;
    }
    
    // 有音乐时自动播放
    audio.play().then(() => {
        component.data.isPlaying = true;
        if (musicDisc) {
            musicDisc.classList.add('spinning');
        }
        console.log('背景音乐自动播放:', component.data.backgroundMusicName);
    }).catch(error => {
        console.warn('背景音乐自动播放失败:', error);
        component.data.isPlaying = false;
        if (musicDisc) {
            musicDisc.classList.remove('spinning');
        }
    });
}

/**
 * 格式化数字显示
 * @param {number} count - 数字
 * @returns {string} 格式化后的字符串
 */
export function formatCount(count) {
    if (count >= 10000) {
        return (count / 10000).toFixed(1) + 'w';
    } else if (count >= 1000) {
        return (count / 1000).toFixed(1) + 'k';
    }
    return count.toString();
}

/**
 * 初始化组件数据
 * @param {VideoInfo} component - 组件实例
 */
export function initializeData(component) {
    component.data = {
        author: component.getAttribute('author') || 'Share-Top用户',
        authorAvatar: component.getAttribute('author-avatar') || '',
        title: component.getAttribute('title') || '',
        description: component.getAttribute('description') || '',
        hashtags: component.getAttribute('hashtags') || '',
        isFollowing: component.getAttribute('following') === 'true',
        isVerified: component.getAttribute('verified') === 'true',
        backgroundMusic: component.getAttribute('background-music') || '',
        backgroundMusicName: component.getAttribute('background-music-name') || '',
        isPlaying: false
    };
}

/**
 * 处理属性变化
 * @param {VideoInfo} component - 组件实例
 * @param {string} name - 属性名
 * @param {string} newValue - 新值
 */
export function handleAttributeChange(component, name, newValue) {
    switch (name) {
        case 'author':
            component.data.author = newValue || 'Share-Top用户';
            break;
        case 'author-avatar':
            component.data.authorAvatar = newValue || '';
            break;
        case 'title':
            component.data.title = newValue || '';
            break;
        case 'description':
            component.data.description = newValue || '';
            break;
        case 'hashtags':
            component.data.hashtags = newValue || '';
            break;
        case 'following':
            component.data.isFollowing = newValue === 'true';
            break;
        case 'verified':
            component.data.isVerified = newValue === 'true';
            break;
        case 'background-music':
            component.data.backgroundMusic = newValue || '';
            // 更新音频源
            const audio = component.shadowRoot.querySelector('.background-audio');
            if (audio) {
                audio.innerHTML = newValue ? `<source src="${newValue}" type="audio/mpeg">` : '';
                audio.load();
                // 音频加载完成后自动播放
                audio.addEventListener('loadeddata', () => {
                    autoPlayMusic(component);
                }, { once: true });
            }
            // 如果没有音乐源，立即调用自动播放逻辑来停止播放
            if (!newValue) {
                autoPlayMusic(component);
            }
            break;
        case 'background-music-name':
            component.data.backgroundMusicName = newValue || '';
            break;
    }
}